<template>
  <ele-page>
    <!-- 搜索表单 -->
    <search
      @search="reload"
      :where="defaultWhere"
      v-if="search"
      :badge-data="badgeData"
    />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        highlight-current-row
        border
        :where="defaultWhere"
      >
        <template #toolbar>
          <el-button
            v-if="props.action == 'list'"
            type="success"
            class="ele-btn-icon"
            :icon="Plus"
            @click="openEdit()"
          >
            新建
          </el-button>
          <el-button
            v-if="props.action == 'judge' && status == 0"
            type="success"
            @click="pass()"
          >
            通过选中
          </el-button>
          <el-button
            v-if="props.action == 'judge' && status == 0"
            type="danger"
            @click="openReject(null)"
          >
            拒绝选中的行
          </el-button>
        </template>

        <template #status="{ row }">
          {{ row.id }}<br />
          <el-tag :type="row.statusType">{{ row.statusText }}</el-tag>
        </template>

        <template #belongs_date="{ row }">
          <span class="dark">{{ row.id }}</span> <br />
          {{ row.belongsDate }}
        </template>

        <template #belongs="{ row }">
          <span v-if="row.belongs == '总部'">总部</span>
          <span v-else>{{ row.area }}{{ row.company }}</span>
        </template>

        <template #amount="{ row }">
          {{ row.amount }} <br />
          {{ row.remark }}<br />
          <span class="pointer blue" @click="openImages(row.imageList)">
            查看凭证
          </span>
        </template>

        <template #images="{ row }">
          <span class="pointer blue" @click="openImages(row.imageList)">
            查看凭证
          </span>
        </template>

        <template #judgeTimes="{ row }">
          <span class="pointer blue" @click="openJudgeLogs(row)">
            {{ row.judge_times }}
          </span>
        </template>

        <template #create="{ row }">
          {{ row.create_user }} - {{ row.create_time }}
        </template>

        <template #done="{ row }">
          {{ row.done_user }} <br />
          {{ row.done_time }}
        </template>

        <template #reject="{ row }">
          {{ row.reject_user }} <br />
          {{ row.reject_time }}
        </template>

        <template #action="{ row }">
          <el-button-group>
            <el-button
              type="info"
              size="small"
              @click="openEdit(row)"
              v-if="props.action == 'list'"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="del(row)"
              v-if="props.action == 'list'"
            >
              删除
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="pass(row, 200)"
              v-if="props.action == 'judge' && row.status == 0"
            >
              通过
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="openReject(row)"
              v-if="props.action == 'judge' && row.status == 0"
            >
              拒绝
            </el-button>
          </el-button-group>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 编辑弹窗 -->
    <Edit v-model="showEdit" :data="current" @done="reload" />
    <Reject v-model="showReject" :data="current" @done="rejectDone" />
    <Images v-model="showImages" :data="current" />
  </ele-page>
</template>

<script setup>
  import { ref, computed } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import Search from './search.vue';
  import Edit from './edit.vue';
  import Reject from './reject.vue';
  import Images from './images.vue';
  import {
    pageCompanyIncomeExpense,
    removeCompanyIncomeExpense,
    passCompanyIncomeExpense
  } from '@/api/company';
  import { ElMessageBox } from 'element-plus/es';
  import { EleMessage } from 'ele-admin-plus/es';

  const props = defineProps({
    search: {
      type: Boolean,
      default: true
    },
    action: {
      type: String,
      default: 'list'
    },
    companyId: {
      type: String,
      default: ''
    },
    tenantId: {
      type: String,
      default: ''
    },
    belongsDate: {
      type: String,
      default: ''
    },
    actionStatus: Number
  });

  /** 表格实例 */
  const tableRef = ref(null);

  /** 表格列配置 */
  const columns = computed(() => {
    const cols = [];
    if (status.value == 0 && props.action == 'judge') {
      cols.push({
        type: 'selection',
        columnKey: 'selection',
        width: 50,
        align: 'center',
        fixed: 'left'
      });
    }
    cols.push(
      {
        prop: 'id',
        label: 'ID',
        width: 80
      },
      {
        prop: 'belongs_date',
        label: '费用日期',
        width: 105,
        align: 'center'
      },
      {
        prop: 'cate',
        label: '分类',
        width: 100
      },
      {
        slot: 'belongs',
        label: '所属',
        width: 220
      },
      {
        prop: 'remark',
        label: '费用说明'
      },
      {
        prop: 'amount',
        label: '金额',
        width: 120
      },
      {
        slot: 'images',
        label: '凭证',
        width: 90
      },
      {
        prop: 'create_user',
        label: '录入人',
        width: 90
      },
      {
        prop: 'create_time',
        label: '录入日期',
        width: 120
      }
    );

    if (status.value == 500) {
      cols.push(
        {
          prop: 'reject_reason',
          label: '拒绝原因',
          width: 90
        },
        {
          prop: 'reject_user',
          label: '拒绝人',
          width: 90
        },
        {
          prop: 'reject_time',
          label: '拒绝日期',
          width: 120
        }
      );
    }

    if (status.value == 200) {
      cols.push(
        {
          prop: 'judge_user',
          label: '审核人',
          width: 90
        },
        {
          prop: 'judge_time',
          label: '审核日期',
          width: 120
        }
      );
    }

    if (status.value == 0) {
      cols.push({
        columnKey: 'action',
        label: '操作',
        width: 140,
        slot: 'action',
        align: 'center',
        fixed: 'right'
      });
    }

    if (status.value == 500 && props.action == 'list') {
      cols.push({
        columnKey: 'action',
        label: '操作',
        width: 140,
        slot: 'action',
        align: 'center',
        fixed: 'right'
      });
    }

    return cols;
  });

  const defaultWhere = {
    tenant_id: props.tenantId,
    status: props.actionStatus,
    company_id: props.companyId,
    belongs_date: props.belongsDate
  };

  /** 表格选中数据 */
  const selections = ref([]);

  /** 当前编辑数据 */
  const current = ref(null);

  /** 是否显示编辑弹窗 */
  const showEdit = ref(false);

  const badgeData = ref(
    Array.from({ length: 191 }, (_, index) => ({ [index]: 0 }))
  );
  console.log(badgeData.value[0]);

  /** 表格数据源 */

  const datasource = async ({ page, where, orders }) => {
    const result = await pageCompanyIncomeExpense({
      ...where,
      ...orders,
      page,
      limit: 99999999
    });
    badgeData.value = result.badgeData;
    return result;
  };

  const showImages = ref(false);
  const openImages = (row) => {
    showImages.value = true;
    current.value = row;
  };

  const showJudgeLogs = ref(false);
  const openJudgeLogs = (row) => {
    showJudgeLogs.value = true;
    current.value = row;
  };

  const status = ref(props.actionStatus);
  /** 搜索 */
  const reload = (where) => {
    selections.value = [];
    status.value = where ? where.status : 0;
    tableRef.value?.reload?.({ page: 1, where });
    console.log(columns, '只能这样了');
  };
  // 拒绝
  const showReject = ref(false);
  const openReject = (row) => {
    const rows = row == null ? selections.value : [row];
    console.log(selections.value);
    if (!rows.length) {
      EleMessage.error('请至少选择一条数据');
      return;
    }

    current.value = rows;
    showReject.value = true;
  };
  const rejectDone = () => {
    showReject.value = false;
    reload();
  };

  /** 打开编辑弹窗 */
  const openEdit = (row) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /** 删除 */
  const del = (row) => {
    ElMessageBox.confirm(
      '确定要删除“' +
        row.company +
        row.position +
        row.amount +
        '”的开支记录吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        removeCompanyIncomeExpense({ id: row.id })
          .then((msg) => {
            EleMessage.success(msg);
            reload();
          })
          .catch((e) => {
            EleMessage.error(e.message);
          });
      })
      .catch(() => {});
  };
  // 通过
  const pass = (row = null) => {
    const rows = row == null ? selections.value : [row];

    if (!rows.length) {
      EleMessage.error('请至少选择一条数据');
      return;
    }
    ElMessageBox.confirm('确定要通过选中的费用吗?', '系统提示', {
      type: 'warning',
      draggable: true
    })
      .then(() => {
        const loading = EleMessage.loading('请求中..');
        var selects = rows.map((d) => d.id);
        var ids = [];
        for (let i = 0; i < selects.length; i++) {
          const v = selects[i];
          ids.push(v);
        }
        ids = JSON.stringify(ids);
        passCompanyIncomeExpense({ ids })
          .then((msg) => {
            loading.close();
            EleMessage.success(msg);
            reload();
          })
          .catch((e) => {
            loading.close();
            EleMessage.error(e.message);
          });
      })
      .catch(() => {});
  };
</script>
